import ssl

import requests
import urllib3

urllib3.disable_warnings()


class HttpHelper:
    server_base_url = ""

    def __init__(self, server_base_url=""):
        self.server_base_url = server_base_url

    def get_base_url(self):
        """
        获取服务的基础URL
        :return:
        """
        return self.server_base_url

    def set_base_url(self, server_base_url):
        """
        设置服务的基础URL
        :param server_base_url:
        :return:
        """
        self.server_base_url = server_base_url

    def get(self, action, key):
        """
        执行HTTP GET请求
        :param key: 请求的资源ID
        :param action:  请求的资源路径
        :return: 请求的响应数据
        """
        try:
            context = ssl.create_default_context()

            context.check_hostname = False

            context.verify_mode = ssl.CERT_NONE

            url = self.server_base_url + action + "/" + key

            print("当前请求的URL为：" + url)

            response = requests.get(url, verify=False)

            if not response.ok:
                raise "HTTP GET请求失败，状态码：" + str(response.status_code)

            return response.content
        except Exception as e:
            raise f"执行HTTP GET {action}请求失败，原因：" + e.message

    @staticmethod
    def post(self, action, data):
        """
        执行HTTP POST请求
        :param action:
        :param self:
        :param data: 请求的数据
        :return: 请求的响应数据
        """
        try:
            url = self.server_base_url + action

            response = requests.post(url, data=data, verify=False)

            if not response.ok:
                raise "HTTP POST请求失败，状态码：" + str(response.status_code)

            return response.content
        except Exception as e:
            raise f"执行HTTP POST {action}请求失败，原因：" + e.message
